﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.CommonAPIs;
namespace Lion.WeiXin.Controllers
{
     [PermissionFilter]
    /// <summary>
    ///  微信用户控制器
    /// </summary>
    public class WeChatUserController : Controller
    {

         DBContext db = new DBContext();

        public ActionResult Index()
        {
            InitProductType(0);

            return View();
        }

        private void InitProductType(int selectID)
        {
            //加载产品类型
            List<DictionaryModel> dic_pro_types = db.Dictionarys.GetList("Dic_Key like '104%' and len(Dic_Key)=6");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });

            foreach (DictionaryModel item in dic_pro_types)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Dic_Value, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Dic_Value });
                }
            }
            ViewData["selData"] = selectTypes;
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(int userGoup, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            List<WeChatUserModel> list = db.WeChatUsers.GetList(string.Empty);
            int totalCount = list.Count;
           // userName = HttpUtility.UrlDecode(userName);
            //如果传入条件参数
            if (userGoup!=0)
            {

                list = list.Where(n => n.Dic_UserGroup == userGoup).OrderByDescending(n => n.AID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();

            }
            else
            {
                list = list.OrderByDescending(n => n.AID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }


        public ActionResult Show()
        {
            string ID = Request.QueryString["ID"];
            if (string.IsNullOrEmpty(ID))
            {
                return Redirect(Request.RawUrl);
            }

            int modelID = int.Parse(ID);
            WeChatUserModel model = db.WeChatUsers.GetModel(modelID);
            return View(model);
        }

       
        public ActionResult Create()
        {
            //1 获取微信所有用户
            SaveStateEnum result = SaveStateEnum.NO;

            try
            {
                List<OpenIdResultJson> allUsers = new List<OpenIdResultJson>();
                string access_token = AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
                OpenIdResultJson openIds = Senparc.Weixin.MP.AdvancedAPIs.User.Get(access_token, string.Empty);
                allUsers.Add(openIds);
                while (!string.IsNullOrEmpty(openIds.next_openid))
                {
                    openIds = Senparc.Weixin.MP.AdvancedAPIs.User.Get(access_token, openIds.next_openid);
                    if (openIds.count > 0)
                    {
                        allUsers.Add(openIds);
                    }
                    
                }
                //获取所有用户分组信息
                List<DictionaryModel> localGroups = db.Dictionarys.GetList("Dic_Key like '104%' and len(Dic_Key)=6");
                //2 获取所有用户详细信息
               // List<WeChatUserModel> localUsers = new List<WeChatUserModel>();

                for (int i = 0; i < allUsers.Count; i++)
                {
                    OpenIdResultJson item = allUsers[i];
                    foreach (string openid in item.data.openid)
                    {
                        WeChatUserModel model = db.WeChatUsers.GetModel(openid);
                        if (model == null)
                        {
                            model = new WeChatUserModel();
                            model.AID = 0;
                        }
                   
                        //获取用户详细信息
                        UserInfoJson wxUserInfo = Senparc.Weixin.MP.AdvancedAPIs.User.Info(access_token, openid);
                        //获取用户分组信息
                        GetGroupIdResult userGoup = Senparc.Weixin.MP.AdvancedAPIs.Groups.GetId(access_token, openid);
                        
                       
                        model.OpenId = wxUserInfo.openid;
                        model.NickName = wxUserInfo.nickname;
                        model.HeadPicture = wxUserInfo.headimgurl;
                        model.Sex = wxUserInfo.sex;
                        model.City = wxUserInfo.city;
                        model.Province = wxUserInfo.province;
                        DictionaryModel localUserGroup = localGroups.FirstOrDefault(n => n.Parameter == userGoup.groupid.ToString());
                        if (localUserGroup != null)
                        {
                            model.Dic_UserGroup =localUserGroup.AID; 
                        }
                      
                        model.IsSubscribe = wxUserInfo.subscribe;
                        model.Subscribe_Date = model.ConvertIntToDate(wxUserInfo.subscribe_time);
                        if (model.AID == 0)
                        {
                            db.WeChatUsers.Add(model);
                        }
                        else {
                            db.WeChatUsers.Update(model);
                        }
                    }
                }

                //保存到本地             
                result = SaveStateEnum.OK;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "用户同步失败");                
            }

            return Content(result.ToString());
        }
         [WeChatFilter]
        public ActionResult SyncUserGroup()
        {
            SaveStateEnum result = SaveStateEnum.NO;
              List<DictionaryModel> localGroups = new List<DictionaryModel>();
            //获取所有用户分组
            try
            {
                string access_token = AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
                GroupsJson userGroupIds = Senparc.Weixin.MP.AdvancedAPIs.Groups.Get(access_token);
                //微信分组在本地的字典表里是 Dic_Key=104 的子节点
                //获取本地分组
                 localGroups = db.Dictionarys.GetList("Dic_Key like '104%' and len(Dic_Key)=6");

                foreach (GroupsJson_Group item in userGroupIds.groups)
                {
                    if (!localGroups.Exists(n => n.Parameter == item.id.ToString()))
                    {
                        DictionaryModel model = new DictionaryModel();
                        model.Dic_Key = db.Dictionarys.GetNewKey("104");
                        model.Dic_Value = item.name;
                        model.Parameter = item.id.ToString();
                        model.Parameter2 = item.count.ToString();
                        model.Creator = CurrentUser.UserName;
                        model.Remark = "微信用户组:参数1=微信分组ID，参数2=分组用户数，Value=分组名称";
                        db.Dictionarys.Add(model);

                        //加入本地组
                        localGroups.Add(model);
                    }
                }
                result = SaveStateEnum.OK;
            }
            catch (Exception ex)
            {

                LogHelper.Error(ex, "同步微信分组错误");
            }
           
            return Json(new{data=localGroups,code=result.ToString() });
        }

        public ActionResult Save(FormCollection form)
        {
            string action = Request.QueryString["Action"];
            string result = SaveStateEnum.OK.ToString();

            WeChatUserModel model = new WeChatUserModel();
            TryUpdateModel(model);
            model.Creator = CurrentUser.UserName;
            try
            {
                if (action == ActionEnum.Create.ToString())
                {
                    if (!db.WeChatUsers.Exists(model.AID))
                    {
                        db.WeChatUsers.Add(model);
                    }
                    else
                    {

                        result = "用户名已存在";
                    }
                }
                else if (action == ActionEnum.Update.ToString())
                {
                    db.WeChatUsers.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    db.WeChatUsers.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }


        public ActionResult BindCard(string openId)
        {
            WeChatUserModel wcUser = db.WeChatUsers.GetModel(openId);
            return View(wcUser);
        }

        public JsonResult SaveBind(string openId, string cardCode)
        {
            if (!db.VipCards.Exists(cardCode))
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "绑定失败，卡号无效！" });
            }

           int count= db.WeChatUsers.GetList(1, string.Format("VipCardCode='{0}'", cardCode), "AID").Count;
           if (count > 0)
           {
               return Json(new { code = SaveStateEnum.NO.ToString(), msg = "绑定失败，此卡已经被绑定！" }); 
           }

            WeChatUserModel wcUser = db.WeChatUsers.GetModel(openId);
            wcUser.VipCardCode = cardCode;
            if (db.WeChatUsers.Update(wcUser))
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "绑定成功！" });
            }
            else {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "绑定失败！" });
            }
        }

        public JsonResult UnBindCard(string openId)
        {
            if (string.IsNullOrEmpty(openId))
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "用户不存在！" });
            }

            WeChatUserModel wcUser = db.WeChatUsers.GetModel(openId);           
            wcUser.VipCardCode = "";
            if (db.WeChatUsers.Update(wcUser))
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "解绑成功！" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "解绑失败！" });
            }
        }

    }
}
